/*
 * @(#)AuthGlobalFilter.java 2021年3月12日
 *
 * Copyright (c) 2010 by rayootech.com. All rights reserved.
 */
package com.nuctech.gateway.filter;

import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;

import cn.hutool.core.util.StrUtil;
import lombok.extern.slf4j.Slf4j;
import reactor.core.publisher.Mono;

/**
 * 自定义全局鉴权过滤器[统一鉴权]
 * 
 * @author lilu
 * @date 2021年3月12日
 * @since 1.0.0
 */
@Slf4j
@Component
public class AuthGlobalFilter implements GlobalFilter, Ordered {

	/**
	 * 标识当前过滤器的优先级，返回值越小，优先级越高
	 * @see org.springframework.core.Ordered#getOrder()
	 */
	@Override
	public int getOrder() {
		return 0;
	}

	/**
	 * 过滤器逻辑
	 * @see org.springframework.cloud.gateway.filter.GlobalFilter#filter(org.springframework.web.server.ServerWebExchange, org.springframework.cloud.gateway.filter.GatewayFilterChain)
	 */
	@Override
	public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
		// 统一鉴权逻辑
		String token = exchange.getRequest().getHeaders().getFirst("token");
		if (StrUtil.isNotBlank(token) && "admin".equals(token)) {
			// 认证成功
			return chain.filter(exchange);
		} else {
			// 认证失败
			log.error("认证失败");
			exchange.getResponse().setStatusCode(HttpStatus.UNAUTHORIZED);
			return exchange.getResponse().setComplete();
		}
	}

}
